#    This is part of WeatherFront.
#
#    Copyright (C) 2010 Stefan Sieber
#
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; version 2 of the License.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License along
#    with this program; if not, write to the Free Software Foundation, Inc.,
#    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#


import objc
import Foundation
import AppKit
import time

import PyFR.Utilities

import urllib2
import re
import string

from WeatherFrontXMLScanner import *



verbose=1
def log(s,level=1):
	if verbose >= level:
		Foundation.NSLog( u"WeatherFrontLog: IpInfoDbDotCom: %@", s ) 
	pass

class IpInfoDbDotComCompiler:
	def __init__(self, xml_stream):
		self = self
		self.xml_stream = xml_stream

	""" Returns the content of a given tag in a stream as SEQUENCE like mySubSet=[]
		The value of the sequence will be an amount of DICTIONARYs like myDict={'DATA': 'Dortmund'} 
		
		Sample
		tmp = self.getSubSet(currentConditions[0], 't') // tag = 't' like for text
		occurence: 4 
		print tmp	 >> [[{'DATA': 'Partly'}, {'DATA': 'Cloudy'}], [{'DATA': 'W'}], [{'DATA': 'Low'}], [{'DATA': 'First'}, {'DATA': 'Quarter'}]] 
		print tmp[2] >> [{'DATA': 'Low'}]
	"""
	def getSubSet(self, stream, tag):
		occurCounter=0
		i=0
		startPos=[]
		endPos=[]
		#print i, startPos, endPos, tag
		#print "***\n", stream, "***\n"
		for item in stream:
			i+=1
			if item.has_key(tag):
				if item.get(tag) == 'START':
					occurCounter += 1
					startPos.append(i)
				if item.get(tag) == 'END':
					endPos.append(i-1)
		#print occurCounter, startPos, endPos
		i=0
		returnValue=[]
		while i < occurCounter:
			returnValue.append(stream.__getslice__(startPos[i],endPos[i]))
			i+=1;
		return returnValue
	
	"""
		getCurrentLocation 
	"""
	def getCurrentLocation(self, weatherAPI):
		value = []
		i = 0
		
		resp = ""
		resp = self.getSubSet(self.xml_stream, 'Response')
		
		#log(resp)
		
		for item in (self.getSubSet(resp[0], 'City'))[0]: # km/h mp/h
			log("City: %s" % item.get('DATA'))
			weatherAPI.city = item.get('DATA')
		for item in (self.getSubSet(resp[0], 'CountryName'))[0]: # km/h mp/h
			log("Country: %s" % item.get('DATA'))
			weatherAPI.country = item.get('DATA')
		for item in (self.getSubSet(resp[0], 'RegionName'))[0]: # km/h mp/h
			log("Region: %s" % item.get('DATA'))
			weatherAPI.state = item.get('DATA')
			
			
		
	
		